﻿using System;
using System.IO;
using System.IO.Compression;
using System.Text;

namespace HWCDNLogAnalysis.Utils
{
    /// <summary>
    /// 文件工具类
    /// </summary>
    public class FileUtils
    {
        /// <summary>
        /// 读取文件内容
        /// </summary>
        /// <param name="path">文件绝对路径地址</param>
        /// <returns></returns>
        public static string Read(string path)
        {
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                int count = Convert.ToInt32(fs.Length);
                byte[] array = new byte[count];
                fs.Read(array, 0, count);
                return Encoding.UTF8.GetString(array);
            }
        }
        /// <summary>
        /// .gz文件读取内容
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string ReadGZ(string path)
        {
            StringBuilder s = new StringBuilder(102400);
            FileStream fr = File.OpenRead(path);
            GZipStream gzs = new GZipStream(fr, CompressionMode.Decompress);
            byte[] d = new byte[20480];
            int l = gzs.Read(d, 0, 20480);
            while (l > 0)
            {
                s.Append(Encoding.UTF8.GetString(d, 0, l));
                l = gzs.Read(d, 0, 20480);
            }

           
            gzs.Close();
            fr.Close();

            return s.ToString();
        }
        /// <summary>
        /// 多文件下载，并gz压缩后返回
        /// </summary>
        /// <param name="folder">存储地址</param>
        /// <param name="urls">多个下载地址</param>
        /// <returns>返回本地文件地址（绝对地址）</returns>
        public static string FileDown(string folder,List<CDNLog> urls)
        {
            var pathZip = folder + "/tmp/";
            if (!Directory.Exists(pathZip))
            {
                Directory.CreateDirectory(pathZip);
            }
            foreach (var item in urls)
            {
                //获取资料名称
                var dicName = item.Name;

                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(item.Link);
                //根据文件信息中的文件地址获取远程服务器，返回文件流
                var stream = client.GetStreamAsync(item.Link).Result;

                using (FileStream fs = new FileStream(pathZip + "/" + dicName, FileMode.Create))
                {
                    // 复制文件
                    stream.CopyTo(fs);
                    // 清空缓冲区数据
                    fs.Flush();
                }
            }
            //2022071909-res.vgic-itraining.cn-cn.gz
            var _zip = urls[urls.Count-1].Name;
            string _retfile = Path.Combine(folder, _zip);
            //合并文件
            MergeFileAttr(pathZip, _retfile, 1024);

            //删除目录以及目录下的子文件
            //存在即删除
            if (Directory.Exists(pathZip))
            {
                Directory.Delete(pathZip, true);
            }
            return _retfile;
        }
        /// <summary>
        /// 文件合并
        /// </summary>
        /// <param name="path">文件组集合路径</param>
        /// <param name="targetPath">合并之后的保存路径</param>
        /// <param name="SplitFileSize">已多大字节去合并</param>
        public static void MergeFileAttr(string path, string targetPathFile, long SplitFileSize)
        {
            Console.WriteLine("正在合并文件:请稍候......");
            byte[] by = new byte[SplitFileSize];
            DirectoryInfo directory = new DirectoryInfo(path);
            //获取路径下的分割文件集合
            FileInfo[] fileInfos = directory.GetFiles();
            //文件进行排序的集合
            foreach (FileInfo item in fileInfos)
            {
                var fileFullName = item.FullName;
                using (BufferedStream buffered = new BufferedStream(File.OpenRead(fileFullName)))
                {
                    using (BinaryReader stream = new BinaryReader(buffered))
                    {
                        using (BinaryWriter writer = new BinaryWriter(File.Open(targetPathFile, FileMode.Append)))
                        {
                            if (stream.BaseStream.Length != SplitFileSize)
                            {
                                byte[] temp = new byte[stream.BaseStream.Length];
                                stream.BaseStream.Read(temp, 0, temp.Length);
                                writer.Write(temp);
                            }
                            else
                            {
                                stream.BaseStream.Read(by, 0, by.Length);
                                writer.Write(by);
                            }
                        }
                    }
                }
            }
        }

        public static bool dataGridViewToCSV(DataGridView dataGridView)
        {
            if (dataGridView.Rows.Count == 0)
            {
                MessageBox.Show("没有数据可导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "CSV files (*.csv)|*.csv";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.FileName = null;
            saveFileDialog.Title = "保存";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                Stream stream = saveFileDialog.OpenFile();
                StreamWriter sw = new StreamWriter(stream, System.Text.Encoding.UTF8);
                string strLine = "";
                try
                {
                    //表头
                    for (int i = 0; i < dataGridView.ColumnCount; i++)
                    {
                        if (i > 0)
                            strLine += ",";
                        strLine += dataGridView.Columns[i].HeaderText;
                    }
                    strLine.Remove(strLine.Length - 1);
                    sw.WriteLine(strLine);
                    strLine = "";
                    //表的内容
                    for (int j = 0; j < dataGridView.Rows.Count; j++)
                    {
                        strLine = "";
                        int colCount = dataGridView.Columns.Count;
                        for (int k = 0; k < colCount; k++)
                        {
                            if (k > 0 && k < colCount)
                                strLine += ",";
                            if (dataGridView.Rows[j].Cells[k].Value == null)
                                strLine += "";
                            else
                            {
                                string cell = dataGridView.Rows[j].Cells[k].Value.ToString().Trim();
                                //防止里面含有特殊符号
                                cell = cell.Replace("\"", "\"\"");
                                cell = "\"" + cell + "\"";
                                strLine += cell;
                            }
                        }
                        sw.WriteLine(strLine);
                    }
                    sw.Close();
                    stream.Close();
                    MessageBox.Show("数据被导出到：" + saveFileDialog.FileName.ToString(), "导出完毕", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "导出错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }
            }
            return true;
        }
    }
}
